# -*- coding: utf-8 -*-
import time
import datetime
from odoo import http
from odoo.http import request
from dateutil import tz
import jinja2
import logging
import json

_logger = logging.getLogger(__name__)

loader = jinja2.PackageLoader('odoo.addons.lift_base', "views/jinja")

env = jinja2.Environment(loader=loader, autoescape=True)
env.filters["json"] = json.dumps

class Controller(http.Controller):

    # 陈师傅测试用start
    @http.route('/iflogin', csrf="*", auth='public')
    def iflogin(self, **kw):
        # 首先判断存不存在session
        _logger.warning('~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
        _logger.warning(request.session)
        _logger.warning('~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
        code = request.session['uid']
        # request.session['uid'] = 1
        # request.session['login'] = 'admin'
        # request.session['password'] = 'admin'
        return json.dumps({'err': 0}) if request.session['uid'] else json.dumps({'err': 1})

    @http.route('/tylogin', csrf="*", auth='public')
    def tylogin(self, **kw):
        # 把登录信息写进session
        request.session['uid'] = 1
        request.session['login'] = 'admin'
        request.session['password'] = 'admin'
        _logger.warning('~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
        for k in kw:
            _logger.warning(k)
        _logger.warning('~~~~~~~~~~~~~~~~~~~~~~~~~~~~')
        return json.dumps({'err': 0})

    @http.route('/tedef', type='json', auth='public')
    def tedef(self, **kw):
        _logger.warning(request.session)
        code = request.session['uid']
        return json.dumps({'err': 2})
    # 陈师傅测试用end

    @http.route("/web/use/company/register/view", auth="public", type="http", csrf=False)
    def use_company_register_view(self, **kw):
        province_ids = request.env["tyibs.base.province"].sudo().search([])
        result=[{"id": item.id, "name": item.name} for item in province_ids]
        # for province in province_ids:
        #     result.append({"province_id": province.id, "province_name": province.name,
        #                    "city_ids": [{"city_id": city.id, "city_name": city.name,
        #                                  "area_ids": [{"area_id": area.id, "area_name": area.name}
        #                                               for area in city.area_ids] }
        #                                 for city in province.city_ids]})
        return env.get_template("use_company_register.html").render({"result": result})

    @http.route("/web/get/city/by/province", auth="public", csrf=False)
    def get_city_by_province(self, **kw):
        province_id = kw.get("province_id", False)
        province_id = province_id if province_id else False
        citys = request.env["tyibs.base.province.city"].sudo().search([("province_id", "=", int(province_id))])
        return json.dumps({"citys":[{"id": item.id, "name": item.name} for item in citys]})

    @http.route("/web/get/area/by/city", auth="public", csrf=False)
    def get_area_by_city(self, **kw):
        city_id = kw.get("city_id")
        city_id = city_id if city_id else False
        areas = request.env["tyibs.base.province.city.area"].sudo().search([("city_id", "=", int(city_id))])
        return json.dumps({"areas":[{"id": item.id, "name": item.name} for item in areas]})

    @http.route("/web/search/use/company", auth="public", csrf=False)
    def search_use_company(self, **kw):
        company_name = kw.get("company_name")
        use_company_ids = request.env["tyibs.base.lift.use.company"].sudo().search([('name', 'ilike', company_name)], limit=10)
        return json.dumps({"use_companies": [{"id": item.id, "name": item.name} for item in use_company_ids]})

    @http.route("/web/get/use/company", auth="public", csrf=False)
    def get_use_company(self, **kw):
        id = kw.get("id")
        use_company = request.env["tyibs.base.lift.use.company"].sudo().browse(int(id))
        def format_str(str):
            return str if str else ""
        return json.dumps({
            "name": use_company.name,
            "trust_code": format_str(use_company.trust_code),
            "province_id": use_company.province_id.id,
            "city_id": use_company.city_id.id,
            "area_id": use_company.area_id.id,
            "address_detail": format_str(use_company.address_detail),
            "linkman": format_str(use_company.linkman),
            "linkman_phone": format_str(use_company.linkman_phone),
            "linkman_tel": format_str(use_company.linkman_tel),
            "linkman_email": format_str(use_company.linkman_email)
        })

    @http.route("/web/use/company/register", auth="public", csrf=False)
    def use_company_register(self, **kw):
        result={"result": True}
        try:
            kw["province_id"] = int(kw.get("province_id"))
            kw["city_id"] = int(kw.get("city_id"))
            kw["area_id"] = int(kw.get("area_id"))
            kw["use_company_id"] = int(kw.get("use_company_id"))
            request.env["tyibs.base.filing.user.company.apply"].sudo().create(kw)
        except Exception, e:
            result["result"] = False
            result["error_msg"] = e.message if e.message else e.name
        return json.dumps(result)
